import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import {
  Row,
  Col,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Collapse,
  DatePicker,
  PageHeader,
} from 'antd';
import prompt from '@/components/Prompt';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import AntdUpload from '@/components/AntdUpload';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import FileReader from '@/components/FileReader';
import { queryFileList, filterAddFile, filterDeteteFile } from '@/utils/common';
import SearchSelect from '@/components/SearchSelect';
import { columnsEtcCard, getNowFormatDate } from '@/pages/Common/common';
import styles from '@/pages/Operate.less';
import AntdInput from '@/components/AntdInput';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const Panel = Collapse.Panel;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD HH:mm';
@connect(({ manageEtc, common, loading }) => ({
  manageEtc,
  // ownCompany: common.ownCompany,
  dictObject: common.dictObject,
  // id: manageEtc.id,
  loading: loading.effects['manageEtc/etcChangetDetails'],
}))
@Form.create()
export default class ETCOperate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      currentId: '',
      selectedRows: [],
      visible: false,
      fileList: [],
      activeKey: ['1', '2'],
      deleteFileIds: [],
      etcCards: [],
      carInfo: {},
      disabled: false,
    };
    this.fileList = [];
  }
  componentDidMount() {
    const { match, form, dispatch } = this.props;
    const ID = match && match.params ? match.params.id : '';
    this.setState({
      currentId: ID,
    });
    if (ID) {
      this.queryFileList(ID);
      this.getSelectDetails(ID);
    } else {
      form.resetFields();
    }
    // 查询字典：
    //币种：
    dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'currency-type' },
    });
  }
  //详情信息：
  getSelectDetails = ID => {
    this.props.dispatch({
      type: 'manageEtc/etcChangetDetails',
      payload: { id: ID },
      callback: data => {
        if (!data) return;
        this.setFileList(data.attachments);
        this.setState({
          etcCards: [{ id: data.etcId }],
          carInfo: data,
        });
      },
    });
  };

  queryFileList = id => {
    queryFileList({
      props: this.props,
      params: { bizId: id, fileBizType: 'ETC_CHANGE_MANA' },
      callback: data => {
        if (!data) return;
        this.fileList = data;
        this.props.form.setFieldsValue({ fileTokens: data });
      },
    });
  };

  setFileList = list => {
    this.setState({ fileList: list });
  };

  callback = key => {
    this.setState({
      activeKey: key,
    });
  };
  //图片上传end：

  // 上传图片
  handleChange = fileList => {
    this.setState({ fileList });
  };

  // 删除图片
  onRemove = deleteFileIds => {
    this.setState({
      deleteFileIds,
    });
  };
  getValue = values => {
    console.log('卡号--values--',values)
    this.setState({
      etcCards: values,
      carInfo: values[0],
    });
  };

  operatePaneButton = e => {
    e.stopPropagation();
    e.preventDefault();
    const {
      match: { params },
      dispatch,
      manageEtc: { etcChangetDetails },
    } = this.props;
    const currentId = params.id;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { happenTime, exportTime, entranceTime, etcId, fileTokens, ...value } = values;
        const { fileList, deleteFileIds, etcCards, carInfo } = this.state;
        if (etcCards.length > 0) {
          const ectCard = Object.keys(etcCards).length > 1 ? etcCards : carInfo; //用于编辑不重新选择卡号的判断
          value.etcId = ectCard.etcId || ectCard.id;
          value.etcNo = ectCard.etcNo || ectCard.cardNo;
          value.vehicleId = ectCard.vehicleId;
        } else {
          value.etcId = '';
          value.etcNo = '';
          value.vehicleId = '';
        }
        if (happenTime) {
          value.happenTime = moment(happenTime).format(dateFormat);
        }
        if (entranceTime) {
          value.entranceTime = moment(entranceTime).format(dateFormat);
        }
        if (exportTime) {
          value.exportTime = moment(exportTime).format(dateFormat);
        }
        value.fileTokens = filterAddFile(fileTokens);
        value.deleteFileIds = filterDeteteFile(fileTokens, this.fileList);
        if (params.id) {
          value.id = currentId;

          dispatch({
            type: 'manageEtc/EtcChangeOperate',
            payload: value,
            callback: () => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
              this.queryFileList(currentId);
              this.dispatchFun('manageEtc/etcChangeList', {});
            },
          });
        } else {
          dispatch({
            type: 'manageEtc/EtcChangeOperate',
            payload: value,
            callback: res => {
              if (!res) return;
              this.queryFileList(res);
              dispatch({
                type: 'manageEtc/etcChangetDetails',
                payload: { id: res },
                callback: data => {
                  this.setState(preState => ({
                    disabled: !preState.disabled,
                  }));
                  //新增变编辑页面：
                  dispatch({
                    type: 'common/setTabsName',
                    payload: {
                      id: res,
                      name: data.etcChangeNo,
                      isReplaceTab: true,
                    },
                    callback: result => {
                      if (result) {
                        router.push(`/carDaily/manageEtc/etcChangeList/editETCChange/${res}`);
                      }
                    },
                  });
                },
              });
              this.dispatchFun('manageEtc/etcChangeList', {});
            },
          });
        }
      }
    });
  };

  // dispatch 方法
  dispatchFun(type, params) {
    const { dispatch } = this.props;
    dispatch({
      type: type,
      payload: params,
    });
  }

  render() {
    const {
      selectedRowKeys,
      selectedRows,
      visible,
      previewImage,
      fileList,
      papersDetails,
      etcCards,
      carInfo,
      disabled,
    } = this.state;
    const {
      manageEtc: { etcChangetDetails },
      form: { getFieldDecorator },
      dictObject,
      match: { params },
      showType,
    } = this.props;
    const currentId = params.id;
    let selectDetails = etcChangetDetails[currentId];
    const checkDisabled = selectDetails && Object.keys(selectDetails).length > 0 ? true : false;
    const isRecharge =
      selectDetails &&
      (selectDetails.tradingType == 'RECHARGE' || selectDetails.tradingType == '充值')
        ? true
        : false;

    // console.log('isRecharge', isRecharge, 'selectDetails.tradingType', selectDetails.tradingType);

    const genExtraBasicInfo = () => (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <span>{selectDetails ? selectDetails.etcChangeNo : '新增ETC交易'}</span>
        {disabled ? (
          <AdButton
            type="primary"
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="编辑"
            code={selectDetails ? codes.edit : codes.add}
          />
        ) : (
          <Button.Group>
            <AdButton
              type="primary"
              onClick={e => this.operatePaneButton(e)}
              text="保存"
              code={selectDetails ? codes.edit : codes.add}
            />
            {selectDetails && (
              <AdButton
                onClick={() => {
                  this.setState(preState => ({
                    disabled: !preState.disabled,
                  }));
                }}
                text="取消"
                code={selectDetails ? codes.edit : codes.add}
              />
            )}
          </Button.Group>
        )}
      </div>
    );
    const customPanelStyle = {
      borderRadius: 4,
      marginBottom: 12,
      border: 0,
      overflow: 'hidden',
    };
    const prefixSelector = getFieldDecorator('currencyType', {
      initialValue: 'CNY',
    })(
      <Select placeholder="请选择" disabled={true}>
        {dictObject['currency-type'] &&
          dictObject['currency-type'].map(item => (
            <Option key={item.code} value={item.code}>
              {item.value}
            </Option>
          ))}
      </Select>
    );

    const _gutter = { md: 8, lg: 24, xl: 48 };
    const _col = { md: 12, sm: 24 };
    const _row = { md: 24 };

    return (
      <div className={styles.CollapseUpdate}>
        <PageHeaderWrapper title={genExtraBasicInfo()}>
          <Collapse
            activeKey={this.state.activeKey}
            onChange={key => this.callback(key)}
            bordered={false}
          >
            <Panel header="基础信息" key="1" style={customPanelStyle}>
              <div className={styles.tableListForm}>
                <Form layout="inline">
                  <Row gutter={_gutter}>
                    <Col {..._col}>
                      <Form.Item label="单据号码">
                        {getFieldDecorator('etcChangeNo', {
                          initialValue: selectDetails ? selectDetails.etcChangeNo : '',
                        })(<Input placeholder="保存后系统自动生成" disabled={true} />)}
                      </Form.Item>
                    </Col>
                    <Col {..._col}>
                      <Form.Item label="卡号">
                        {getFieldDecorator('etcId', {
                          rules: [{ required: true, message: '请选择' }],
                          initialValue: etcCards,
                        })(
                          <SearchSelect
                            dataUrl="tms/tms-etc-change/etcCard"
                            url="tms/tms-etc-change/etcView_s" // selectedData只只有id时需要传url
                            selectedData={etcCards} // 选中值
                            multiple={false} // 是否多选
                            showValue="cardNo"
                            searchName="keyWord"
                            columns={columnsEtcCard} // 表格展示列
                            onChange={this.getValue} // 获取选中值
                            scrollX={500}
                            id="etcChangeList2"
                            disabled={disabled || checkDisabled}
                            payload={{beActive:1}}
                          />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={_gutter}>
                    <Col {..._col}>
                      <Form.Item label="车牌号">
                        {getFieldDecorator('vehicleId', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue: carInfo.cartPlateNo,
                        })(<Input placeholder="请输入" disabled={true} />)}
                      </Form.Item>
                    </Col>
                    <Col {..._col}>
                      <Form.Item label="所属公司">
                        {getFieldDecorator('ownCompanyName', {
                          initialValue: carInfo.ownCompanyName,
                        })(<Input placeholder="请输入" disabled={true} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
              </div>
            </Panel>

            <Panel header="费用详情" key="2" style={customPanelStyle}>
              <div className={styles.tableListForm}>
                <Form layout="inline">
                  {/* 入口时间 、 入口站 、 出口时间\消费时间 、消费站\出口站 、(交易省份\交易点) 、交易性质 */}

                  {!isRecharge && (
                    <div>
                      <Row gutter={_gutter}>
                        <Col {..._col}>
                          <Form.Item label="入口时间">
                            {getFieldDecorator('entranceTime', {
                              rules: [{ required: true, message: '请输入' }],
                              initialValue:
                                selectDetails && selectDetails.entranceTime
                                  ? moment(selectDetails.entranceTime, dateFormat)
                                  : '',
                            })(
                              <DatePicker
                                showTime
                                format={dateFormat}
                                style={{ width: '100%' }}
                                disabled={disabled}
                              />
                            )}
                          </Form.Item>
                        </Col>
                        <Col {..._col}>
                          <Form.Item label="入口站">
                            {getFieldDecorator('entranceStation', {
                              initialValue: selectDetails ? selectDetails.entranceStation : '',
                            })(<Input placeholder="请输入" disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                      </Row>

                      <Row gutter={_gutter}>
                        <Col {..._col}>
                          <Form.Item label="出口/交易时间">
                            {getFieldDecorator('exportTime', {
                              rules: [{ required: true, message: '请输入' }],
                              initialValue:
                                selectDetails && selectDetails.exportTime
                                  ? moment(selectDetails.exportTime, dateFormat)
                                  : '',
                            })(
                              <DatePicker
                                showTime
                                format={dateFormat}
                                disabled={disabled}
                                style={{ width: '100%' }}
                              />
                            )}
                          </Form.Item>
                        </Col>
                        <Col {..._col}>
                          <Form.Item label="出口站/交易站">
                            {getFieldDecorator('exportStation', {
                              initialValue: selectDetails ? selectDetails.exportStation : '',
                            })(<Input placeholder="请输入" disabled={disabled} />)}
                          </Form.Item>
                        </Col>
                      </Row>
                    </div>
                  )}

                  <Row gutter={_gutter}>
                    {!isRecharge ? (
                      <Col {..._col}>
                        <Form.Item label={'交易省份'}>
                          {getFieldDecorator('locationName', {
                            initialValue: selectDetails ? selectDetails.locationName : '',
                          })(<Input placeholder="请输入" disabled={disabled} />)}
                        </Form.Item>
                      </Col>
                    ) : (
                      <Col {..._col}>
                        <Form.Item label={'充值地点'}>
                          {getFieldDecorator('exportStation', {
                            initialValue: selectDetails ? selectDetails.exportStation : '',
                          })(<Input placeholder="请输入" disabled={disabled} />)}
                        </Form.Item>
                      </Col>
                    )}
                    <Col {..._col}>
                      <Form.Item label="金额">
                        {getFieldDecorator('changeMoney', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue: selectDetails ? selectDetails.changeMoney : '',
                        })(
                          <AntdInput
                            mode="money"
                            label="金额"
                            placeholder="长度不超过18位可保留两位小数"
                            addonBefore={prefixSelector}
                            disabled={disabled}
                          />
                        )}
                      </Form.Item>
                    </Col>

                    {/* <Col {..._col}>
                      <Form.Item label="车次号">
                        {getFieldDecorator('trainNo', {
                          initialValue: selectDetails ? selectDetails.trainNo : '',
                        })(<Input placeholder="请输入" />)}
                      </Form.Item>
                    </Col> */}
                  </Row>
                  {/* <Row gutter={_gutter}>
                    <Col {..._col}>
                      <Form.Item label="交易时间">
                        {getFieldDecorator('happenTime', {
                          rules: [{ required: true, message: '请输入' }],
                          initialValue:
                            selectDetails && selectDetails.happenTime
                              ? moment(selectDetails.happenTime, dateFormat)
                              : '',
                        })(<DatePicker showTime format={dateFormat} style={{ width: '100%' }} />)}
                      </Form.Item>
                    </Col>
                  </Row> */}
                  <Row gutter={_gutter}>
                    <Col {..._row}>
                      <Form.Item label="备注">
                        {getFieldDecorator('remarks', {
                          initialValue: selectDetails ? selectDetails.remarks : '',
                        })(<TextArea placeholder="请输入" rows={4} disabled={disabled} />)}
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={_gutter}>
                    <Col {..._row}>
                      <Form.Item label="票据">
                        {getFieldDecorator('fileTokens')(
                          <FileReader disabled={disabled} urlType="tms" />
                        )}
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
              </div>
            </Panel>
          </Collapse>
        </PageHeaderWrapper>
      </div>
    );
  }
}
